package com.lzx.iteam;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.WifiInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.lzx.iteam.adapter.AttendanceSubSignAdapter;
import com.lzx.iteam.adapter.AttendanceTeamAdapter;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.bean.AttendanceSubBean;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.MyListView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * Created by Megan on 16/4/7.
 */
public class AttendanceMainActivity extends Activity implements View.OnClickListener, AttendanceSubSignAdapter.SubSignListener {

    private String Tag = "AttendanceMainActivity";

    private ImageView mIvArrow, mIvSignIn, mIvSignOut, mIvLocIcon;
    private TextView mTvTitle, mTvManage, mTvCount, mTvCurrentWeek, mTvCurrentDate, mTvLocation, mTvLocNote, mTvLocAddress, mTvSignIn, mTvSignOut, mTvSignInOk, mTvSignOutOk, mTvSignInTime, mTvSignOutTime, mTvLegworkIn;
    private TextView mTvSignInTitle, mTvSignOutTitle, mTvSignNoonInTitle, mTvSignNoonOutTitle;
    private TextView mTvSignNoonInTime, mTvSignNoonOutTime;
    private TextView mTvSignNoonIn, mTvSignNoonOut;
    private TextView mTvSignNoonInOk, mTvSignNoonOutOk;
    private TextView mTvNullSub;
    private ImageView mIvSignNoonIn, mIvSignNoonOut;
    private TextView mTvWifi;
    private Button mBtnLocRefresh;
    private LinearLayout mLayoutNoon;
    private LinearLayout mLlTitle, mLlBack, mLlHelp;
    private LinearLayout mLayoutAttendance;
    private MyListView mLvSubClass;
    private RelativeLayout mRlWifiLayout, mRlTitleLayout, mRlLocLayout;
    private RelativeLayout mRlGuide;

    private PopupWindow mCountPopupWindow;
    private Dialog mTeamDialog;
    private LocationUtil mLocationUtil;
    private Dialog mProgressDialog;
    private PreferenceUtil mPreferenceUtil;

    private AttendanceData attendanceData;
    private ArrayList<Object> attendanceDatas;
    private ArrayList<AttendanceSubBean> mSubClass;
    private AttendanceSubSignAdapter mSubSignAdapter;
    private AttendanceSubBean mAttendanceSubBean;

    private int mPosition = -1;  // 班次Index
    private double mLatitude, mLongitude;
    private String mGroupId;
    private String deviceId;
    private String deviceName;
    private String wifiMac;
    private String mReceiverGroupId;
    private String mReceiverGroupName;
    private String mAction;
    private String mSubName;
    private boolean mIsAttendanceWifi;

    private long mOneDayTime = 24 * 60 * 60; // 一天的秒数
    private int mNoonFlag;  // flag. 0:两次签到   1：四次签到
    private final int GET_ATTENDANCE_FACE = 1000;
    private final int GET_ATTENDANCE_DO = 1001;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GET_ATTENDANCE_FACE:
                    waitDlgDismiss();
                    if (msg.arg1 == 0) {
                        attendanceDatas = (ArrayList<Object>) msg.obj;
                        if (attendanceDatas != null && attendanceDatas.size() > 0) {
                           /* if ("my_receiver".equals(mAction)) {
                                for (AttendanceData data : attendanceDatas) {
                                    if ((!StringUtil.isEmpty(mReceiverGroupId)) && mReceiverGroupId.equals(data.getGroupId())) {
                                        attendanceData = data;
                                    }
                                }
                            } else {*/
                            mGroupId = PreferenceUtil.getInstance(AttendanceMainActivity.this).getString(PreferenceUtil.ATTENDANCE_GROUP_ID, "");
                            if (!StringUtil.isEmpty(mGroupId)) {
                                for (int i = 0; i < attendanceDatas.size(); i++) {
                                    AttendanceData attendance = (AttendanceData) attendanceDatas.get(i);
                                    if (mGroupId.equals(attendance.getGroupId())) {
                                        attendanceData = attendance;
                                        break;
                                    }
                                }
                            }
                            if (StringUtil.isEmpty(mGroupId) || attendanceData == null) {
                                attendanceData = (AttendanceData) attendanceDatas.get(0);
                                mGroupId = attendanceData.getGroupId();
                            }
                           /* }*/
                            mIvArrow.setVisibility(View.VISIBLE);
                            setAttendanceMsg();
                        } else {
                            mTvNullSub.setVisibility(View.VISIBLE);
                            mTvNullSub.setText("您未被加入考勤点，请联系管理员");
                            mIvArrow.setVisibility(View.GONE);
                            mIvSignIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                            mIvSignOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                        }
                    } else {
                        if (msg.arg1 == AsynHttpClient.ERROR_LOCAL) {
                            Toast.makeText(AttendanceMainActivity.this, R.string.active_failure_no_network,
                                  Toast.LENGTH_LONG).show();
                        } else {
                            Toast.makeText(AttendanceMainActivity.this, (String) msg.obj,
                                  Toast.LENGTH_LONG).show();
                        }
                    }
                    break;
                case GET_ATTENDANCE_DO:
                    if (msg.arg1 == 0) {

                        if (attendanceData.getFormType() == 1) { // 排班打卡
                            AttendanceSubBean bean = mSubClass.get(mPosition);
                            bean.setSign(true);
                            long currentTime = System.currentTimeMillis() / 1000;
                            bean.setSignTime(currentTime);
                            if (currentTime > bean.getTime()) {
                                bean.setLate(true);
                            } else {
                                bean.setLate(false);
                            }
                            mSubClass.set(mPosition, bean);
                            mSubSignAdapter.bindData(mSubClass);

                            attendanceDatas.remove(attendanceData);
                            attendanceData.setSubFormList(mSubClass);
                            attendanceDatas.add(attendanceData);

                        } else { // 固定班次打卡
                            if (msg.arg2 == 1) { // 上午签到打卡
                                mIvSignIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                                attendanceDatas.remove(attendanceData);
                                long currentTime = System.currentTimeMillis();
                                attendanceData.setSignInTime(currentTime / 1000 + "");
                                attendanceDatas.add(attendanceData);
                                mTvSignIn.setVisibility(View.GONE);
                                mTvSignInOk.setVisibility(View.VISIBLE);
                                mTvSignInOk.setText("已打卡 " + DateUtil.getHourAndMin(System.currentTimeMillis()));

                                if (isWordDay(attendanceData.getWorkDate())) {
                                    if (compareDate(currentTime / 1000 + "", attendanceData.getStartWorkTime())) {
                                        mTvSignInOk.setTextColor(getResources().getColor(R.color.red));
                                    }
                                }

                            } else if (msg.arg2 == 2) { // 下午签退打卡
                                mIvSignOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                                attendanceDatas.remove(attendanceData);
                                long currentTime = System.currentTimeMillis();
                                attendanceData.setSignOutTime(currentTime / 1000 + "");
                                attendanceDatas.add(attendanceData);
                                mTvSignOut.setVisibility(View.GONE);
                                mTvSignOutOk.setVisibility(View.VISIBLE);
                                mTvSignOutOk.setText("已打卡 " + DateUtil.getHourAndMin(System.currentTimeMillis()));

                                if (isWordDay(attendanceData.getWorkDate())) {
                                    if (compareDate(attendanceData.getEndWorkTime(), currentTime / 1000 + "")) {
                                        mTvSignOutOk.setTextColor(getResources().getColor(R.color.red));
                                    }
                                }
                            } else if (msg.arg2 == 3) { // 上午签退打卡
                                mIvSignNoonOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                                attendanceDatas.remove(attendanceData);

                                long currentTime = System.currentTimeMillis();
                                attendanceData.setNoonSignOutTime(currentTime / 1000 + "");
                                attendanceDatas.add(attendanceData);
                                mTvSignNoonOut.setVisibility(View.GONE);
                                mTvSignNoonOutOk.setVisibility(View.VISIBLE);
                                mTvSignNoonOutOk.setText("已打卡 " + DateUtil.getHourAndMin(currentTime));

                                if (isWordDay(attendanceData.getWorkDate())) {

                                    if (compareDate(attendanceData.getNoonEndTime(), currentTime / 1000 + "")) {
                                        mTvSignNoonOutOk.setTextColor(getResources().getColor(R.color.red));
                                    }
                                }


                            } else if (msg.arg2 == 4) { // 下午签到打卡
                                mIvSignNoonIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                                attendanceDatas.remove(attendanceData);
                                long currentTime = System.currentTimeMillis();
                                attendanceData.setNoonSignInTime(currentTime / 1000 + "");
                                attendanceDatas.add(attendanceData);
                                mTvSignNoonIn.setVisibility(View.GONE);
                                mTvSignNoonInOk.setVisibility(View.VISIBLE);
                                mTvSignNoonInOk.setText("已打卡 " + DateUtil.getHourAndMin(currentTime));

                                if (isWordDay(attendanceData.getWorkDate())) {
                                    if (compareDate(currentTime / 1000 + "", attendanceData.getNoonStartTime())) {
                                        mTvSignNoonInOk.setTextColor(getResources().getColor(R.color.red));
                                    }
                                }
                            }
                        }

                    } else {
                        Toast.makeText(AttendanceMainActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.attendance_main_layout);
        initViews();
        setData();
        getCurDeviceMsg();
    }

    private void initViews() {
        mLlTitle = (LinearLayout) findViewById(R.id.ll_attendance_main_title);
        mLlHelp = (LinearLayout) findViewById(R.id.attendance_ll_help);
        mIvArrow = (ImageView) findViewById(R.id.iv_attendance_arrow);
        mIvLocIcon = (ImageView) findViewById(R.id.iv_attendance_main_loc_icon);
        mTvTitle = (TextView) findViewById(R.id.tv_attendance_main_team);
        mTvManage = (TextView) findViewById(R.id.tv_attendance_main_manage);
        mTvCount = (TextView) findViewById(R.id.tv_attendance_main_count);
        mTvCurrentDate = (TextView) findViewById(R.id.tv_attendance_main_current_date);
        mTvCurrentWeek = (TextView) findViewById(R.id.tv_attendance_main_current_week);
        mTvLocation = (TextView) findViewById(R.id.tv_attendance_main_loc_text);
        mTvLocNote = (TextView) findViewById(R.id.tv_attendance_main_loc_note);//隐藏
        mTvLocAddress = (TextView) findViewById(R.id.tv_attendance_main_loc_address);//隐藏
        mBtnLocRefresh = (Button) findViewById(R.id.btn_attendance_main_refresh);

        mIvSignIn = (ImageView) findViewById(R.id.iv_attendance_main_sign_in);
        mTvSignInTitle = (TextView) findViewById(R.id.tv_attendance_main_sign_in_title);
        mTvSignIn = (TextView) findViewById(R.id.tv_attendance_main_sign_in);
        mTvSignInOk = (TextView) findViewById(R.id.tv_attendance_main_sign_in_ok);
        mTvSignInTime = (TextView) findViewById(R.id.tv_attendance_main_sign_in_time);

        mIvSignOut = (ImageView) findViewById(R.id.iv_attendance_main_sign_out);
        mTvSignOutTitle = (TextView) findViewById(R.id.tv_attendance_main_sign_out_title);
        mTvSignOut = (TextView) findViewById(R.id.tv_attendance_main_sign_out);
        mTvSignOutOk = (TextView) findViewById(R.id.tv_attendance_main_sign_out_ok);
        mTvSignOutTime = (TextView) findViewById(R.id.tv_attendance_main_sign_out_time);

        mLayoutNoon = (LinearLayout) findViewById(R.id.ll_attendance_noon);

        mIvSignNoonIn = (ImageView) findViewById(R.id.iv_attendance_main_noon_sign_in);
        mTvSignNoonInTitle = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_in_title);
        mTvSignNoonIn = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_in);
        mTvSignNoonInOk = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_in_ok);
        mTvSignNoonInTime = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_in_time);

        mIvSignNoonOut = (ImageView) findViewById(R.id.iv_attendance_main_noon_sign_out);
        mTvSignNoonOutTitle = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_out_title);
        mTvSignNoonOut = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_out);
        mTvSignNoonOutOk = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_out_ok);
        mTvSignNoonOutTime = (TextView) findViewById(R.id.tv_attendance_main_noon_sign_out_time);

        mTvNullSub = (TextView) findViewById(R.id.tv_attendance_main_null_sub);
        mTvLegworkIn = (TextView) findViewById(R.id.tv_attendance_main_legwork_in);
        mLlBack = (LinearLayout) findViewById(R.id.ll_attendance_main_back);
        mRlWifiLayout = (RelativeLayout) findViewById(R.id.rl_attendance_main_wifi);
        mTvWifi = (TextView) findViewById(R.id.tv_attendance_main_wifi_text);
        mRlTitleLayout = (RelativeLayout) findViewById(R.id.rl_attendance_main_title_layout);
        mRlLocLayout = (RelativeLayout) findViewById(R.id.rl_attendance_main_loc);
        mRlGuide = (RelativeLayout) findViewById(R.id.rl_attendance_main_guide);

        mLayoutAttendance = (LinearLayout) findViewById(R.id.ll_attendance_main);
        mLvSubClass = (MyListView) findViewById(R.id.lv_attendance_main);

        mLlHelp.setOnClickListener(this);
        mLlTitle.setOnClickListener(this);
        mTvManage.setOnClickListener(this);
        mTvCount.setOnClickListener(this);
        mBtnLocRefresh.setOnClickListener(this);
        mTvSignIn.setOnClickListener(this);
        mTvSignOut.setOnClickListener(this);
        mTvSignNoonIn.setOnClickListener(this);
        mTvSignNoonOut.setOnClickListener(this);
        mTvLegworkIn.setOnClickListener(this);
        mLlBack.setOnClickListener(this);

        waitDlgShow();

        /*mLatitude = 40.067981;
        mLongitude = 116.42209;
        getAttendanceFace();*/

        mPreferenceUtil = PreferenceUtil.getInstance(this);
        mLocationUtil = new LocationUtil(this);
        mLocationUtil.setListener(new LocationUtil.LocationStatus() {

            @Override
            public void onLocated(BDLocation location) {
                if (location == null) {
                    return;
                }
                Log.d(Tag, "当前位置经纬度：latitude=" + location.getLatitude() + ",longitude=" + location.getLongitude() + ",address" + location.getAddress() + ",addrStr" + location.getAddrStr());
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();

                getAttendanceFace();
            }
        });

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_attendance_main_title:
                if (attendanceData != null) {
                    if (mIvArrow.getDrawable().getCurrent().getConstantState()
                          .equals(getResources().getDrawable(R.drawable.arrow_up).getConstantState())) {
                        mIvArrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        mIvArrow.setImageResource(R.drawable.arrow_up);
                        if (attendanceDatas != null && attendanceDatas.size() > 0) {
                            showTeamDialog();
                        }
                    }
                }
                break;
            case R.id.tv_attendance_main_manage:
                if (attendanceData != null) {
                    Intent intent = new Intent(AttendanceMainActivity.this, AttendanceManageActivity.class);
                    intent.putExtra("attendanceData", attendanceData);
                    startActivityForResult(intent, 100);
                } else {
                    Toast.makeText(this, "您不属于任何考勤点，无法进行考勤操作", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.tv_attendance_main_count:
                if (mRlGuide.getVisibility() == View.VISIBLE) {
                    mRlGuide.setVisibility(View.GONE);
                }
                if (attendanceData != null) {
                    showAttendanceCountPop();
                } else {
                    Toast.makeText(this, "您不属于任何考勤点，无法进行考勤操作", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_attendance_main_refresh:
                refreshLoction("0");
                break;
            case R.id.tv_attendance_main_sign_in:
                if (!checkAttendanceData()) {
                    return;
                }
                if (attendanceData != null) {
                    if (!"0".equals(attendanceData.getSignInTime())) {
                        Toast.makeText(this, "您今天已经签到，请勿重复打卡", Toast.LENGTH_LONG).show();
                    } else {
                        if (isWordDay(attendanceData.getWorkDate())) {
                            if (compareDate(System.currentTimeMillis() / 1000 + "", attendanceData.getStartWorkTime())) {
                                showNoticeDlg("现在是" + DateUtil.getHourAndMin(System.currentTimeMillis()) + "分,您已迟到\n是否确认签到", 1);
                            } else {
                                refreshLoction("1");
                            }
                        } else {
                            refreshLoction("1");
                        }
                    }
                }
                break;
            case R.id.tv_attendance_main_sign_out:
                if (!checkAttendanceData()) {
                    return;
                }
                if (attendanceData != null) {
                    if (!"0".equals(attendanceData.getSignOutTime())) {
                        Toast.makeText(this, "您今天已经签退，请勿重复打卡", Toast.LENGTH_LONG).show();
                    } else {
                        if (isWordDay(attendanceData.getWorkDate())) {
                            if (compareDate(attendanceData.getEndWorkTime(), System.currentTimeMillis() / 1000 + "")) {
                                showNoticeDlg("现在是" + DateUtil.getHourAndMin(System.currentTimeMillis()) + "分,还未下班\n您是否确认签退", 2);
                            } else {
                                refreshLoction("2");
                            }
                        } else {
                            refreshLoction("2");
                        }
                    }
                }
                break;
            case R.id.tv_attendance_main_noon_sign_out:
                if (!checkAttendanceData()) {
                    return;
                }
                if (attendanceData != null) {
                    if (!"0".equals(attendanceData.getNoonSignOutTime())) {
                        Toast.makeText(this, "您今天已经签退，请勿重复打卡", Toast.LENGTH_LONG).show();
                    } else {
                        if (isWordDay(attendanceData.getWorkDate())) {
                            if (compareDate(attendanceData.getNoonEndTime(), System.currentTimeMillis() / 1000 + "")) {
                                showNoticeDlg("现在是" + DateUtil.getHourAndMin(System.currentTimeMillis()) + "分,还未下班\n您是否确认签退", 3);
                            } else {
                                refreshLoction("3");
                            }
                        } else {
                            refreshLoction("3");
                        }
                    }
                }
                break;
            case R.id.tv_attendance_main_noon_sign_in:
                if (!checkAttendanceData()) {
                    return;
                }
                if (attendanceData != null) {
                    if (!"0".equals(attendanceData.getNoonSignInTime())) {
                        Toast.makeText(this, "您今天已经签到，请勿重复打卡", Toast.LENGTH_LONG).show();
                    } else {
                        if (isWordDay(attendanceData.getWorkDate())) {
                            if (compareDate(System.currentTimeMillis() / 1000 + "", attendanceData.getNoonStartTime())) {
                                showNoticeDlg("现在是" + DateUtil.getHourAndMin(System.currentTimeMillis()) + "分,您已迟到\n是否确认签到", 4);
                            } else {
                                refreshLoction("4");
                            }
                        } else {
                            refreshLoction("4");
                        }
                    }
                }
                break;
            case R.id.ll_attendance_main_back:
                finish();
                break;
            case R.id.attendance_ll_help:
                Intent intent = new Intent(this, WebViewActivity.class);
                intent.putExtra("title", "如何设置考勤点?");
                intent.putExtra("type", 2);
                startActivity(intent);
                break;
            case R.id.tv_attendance_main_legwork_in:
                toLegworkActivity();
                break;
        }
    }

    /**
     * 进入外勤页面
     */
    private void toLegworkActivity() {
        if (attendanceData != null && attendanceData.getIs_legwork() == 1) {
            Intent legwork = new Intent(AttendanceMainActivity.this, LegworkMainActivity.class);
            legwork.putExtra("group_id", mGroupId);
            legwork.putExtra("form_id", attendanceData.get_id());
            startActivity(legwork);
        } else {
            Toast.makeText(AttendanceMainActivity.this, "该团队尚未开通外勤功能", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 时间比较
     *
     * @param time1
     * @param time2
     * @param time3
     * @param time4
     * @return
     */
    private boolean compareTime(int time1, int time2, int time3, int time4) {
        if (time1 > time3 || (time1 == time3 && time2 > time4)) {
            return true;
        }
        return false;
    }

    /**
     * @param time1
     * @param time2
     * @return
     */
    private boolean compareDate(String time1, String time2) {
        int hour1 = 0;
        int minute1 = 0;
        int hour2 = 0;
        int minute2 = 0;
        if (time1.contains(":")) {
            hour1 = Integer.parseInt(time1.split(":")[0]);
            minute1 = Integer.parseInt(time1.split(":")[1]);
        } else {
            hour1 = DateUtil.getHour(Long.parseLong(time1) * 1000);
            minute1 = DateUtil.getMinute(Long.parseLong(time1) * 1000);
        }

        if (time2.contains(":")) {
            hour2 = Integer.parseInt(time2.split(":")[0]);
            minute2 = Integer.parseInt(time2.split(":")[1]);
        } else {
            hour2 = DateUtil.getHour(Long.parseLong(time2) * 1000);
            minute2 = DateUtil.getMinute(Long.parseLong(time2) * 1000);
        }

        if (hour1 > hour2 || (hour1 == hour2 && minute1 > minute2)) {
            return true;
        }
        return false;
    }


    private void setData() {
        mTvCurrentWeek.setText(DateUtil.getWeek(System.currentTimeMillis()));
        mTvCurrentDate.setText(DateUtil.getYearDate1(System.currentTimeMillis()));
        Intent intent = getIntent();
        mAction = intent.getAction();

        boolean isFrist = mPreferenceUtil.getBoolean("attendance_count_frist", true);
        if (isFrist) {
            mRlGuide.setVisibility(View.VISIBLE);
            mPreferenceUtil.save("attendance_count_frist", false);
        } else {
            mRlGuide.setVisibility(View.GONE);
        }
    }

    /*
            if ("my_receiver".equals(mAction)) {
                mReceiverGroupId = intent.getStringExtra("groupId");
                mReceiverGroupName = intent.getStringExtra("groupName");
            }
    *
    }/
        }

        /**
         * 刷新地址
         * @param type 0:只是刷新，无需走接口   1：上午签到  2：下午签退  3：上午签退  4：下午签到
         */
    private void refreshLoction(final String type) {
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }
        waitDlgShow();

        /*mLatitude = 40.067981;
        mLongitude = 116.42209;
        getAttendanceDoMsg(type);*/

        mLocationUtil = new LocationUtil(this);
        mLocationUtil.setListener(new LocationUtil.LocationStatus() {

            @Override
            public void onLocated(BDLocation location) {
                if (location == null) {
                    return;
                }
                waitDlgDismiss();
                Log.d(Tag, "当前位置经纬度：latitude=" + location.getLatitude() + ",longitude=" + location.getLongitude() + ",address" + location.getAddress() + ",addrStr" + location.getAddrStr());
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();
                if (attendanceData != null) {
                    if ("4.9E-324".equals(mLatitude + "") || "4.9E-324".equals(mLongitude + "")) {
                        mTvLocation.setText("定位失败" + "(" + attendanceData.getDeviation() + "米内有效)");
                    } else {
                        if (getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude())).length() > 3) {
                            mTvLocation.setText("当前定位距离考勤地点" + Double.parseDouble(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) / 1000 + "千米" + "(" + attendanceData.getDeviation() + "米内有效)");
                        } else {
                            mTvLocation.setText("当前定位距离考勤地点" + getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude())) + "米" + "(" + attendanceData.getDeviation() + "米内有效)");
                        }
                        if (Integer.parseInt(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) <= Integer.parseInt(attendanceData.getDeviation())) {
                            mIvLocIcon.setImageDrawable(getResources().getDrawable(R.drawable.attendance_iv_loc_ok));
                        } else {
                            mIvLocIcon.setImageDrawable(getResources().getDrawable(R.drawable.attendance_msg_icon));
                        }
                    }


                }
            }
        });

        setWifiData();
        if (!"0".equals(type)) {
            getAttendanceDoMsg(type);
        }

    }


    /**
     * 弹出中间团队选择
     */
    private void showTeamDialog() {

        mTeamDialog = new AlertDialog.Builder(this)
              .create();
        mTeamDialog.show();
        Window window = mTeamDialog.getWindow();
        WindowManager.LayoutParams lp = mTeamDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f;   // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.attendance_team_pop_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        ListView listView = (ListView) window.findViewById(R.id.lv_attendance_team_list);
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);


        AttendanceTeamAdapter adapter = new AttendanceTeamAdapter(this);
        adapter.bindData(attendanceDatas, 0);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                attendanceData = (AttendanceData) attendanceDatas.get(i);
                mGroupId = attendanceData.getGroupId();
                PreferenceUtil.getInstance(AttendanceMainActivity.this).save(PreferenceUtil.ATTENDANCE_GROUP_ID, mGroupId);
                setAttendanceMsg();
                mTeamDialog.dismiss();
            }
        });

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTeamDialog.dismiss();
            }
        });
        mTeamDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mIvArrow.setImageResource(R.drawable.arrow_down);
            }
        });

    }


    /**
     * 弹出右上角统计操作
     */
    private void showAttendanceCountPop() {
        final View mainView = LayoutInflater.from(this).inflate(R.layout.attendance_count_pop_layout, null);
        LinearLayout myCount = (LinearLayout) mainView.findViewById(R.id.ll_attendance_count_my);
        LinearLayout allCount = (LinearLayout) mainView.findViewById(R.id.ll_attendance_count_all);
        LinearLayout rank = (LinearLayout) mainView.findViewById(R.id.ll_attendance_rank);
        final ImageView guideLeader = (ImageView) mainView.findViewById(R.id.iv_pop_hand_guide_leader);
        final ImageView guideMember = (ImageView) mainView.findViewById(R.id.iv_pop_hand_guide_member);

        if (attendanceData != null && "1".equals(attendanceData.getIsAdmin())) {
            allCount.setVisibility(View.VISIBLE);
            boolean isFrist = mPreferenceUtil.getBoolean("attendance_all_member_frist", true);
            if (isFrist) {
                guideLeader.setVisibility(View.VISIBLE);
                mPreferenceUtil.save("attendance_all_member_frist", false);
            } else {
                guideLeader.setVisibility(View.GONE);
            }

        } else {
            allCount.setVisibility(View.GONE);
            boolean isFrist = mPreferenceUtil.getBoolean("attendance_all_member_frist", true);
            if (isFrist) {
                guideMember.setVisibility(View.VISIBLE);
                mPreferenceUtil.save("attendance_all_member_frist", false);
            } else {
                guideMember.setVisibility(View.GONE);
            }


        }

        myCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (guideMember.getVisibility() == View.VISIBLE) {
                    guideMember.setVisibility(View.GONE);
                }
                Intent intent = new Intent(AttendanceMainActivity.this, AttendanceCalendarActivity.class);
                intent.putExtra("group_id", attendanceData.getGroupId());
                intent.putExtra("form_id", attendanceData.get_id());
                intent.putExtra("form_type", attendanceData.getFormType());
                intent.putExtra("sub_name", mSubName);
                startActivity(intent);
                mCountPopupWindow.dismiss();
            }
        });
        allCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (guideLeader.getVisibility() == View.VISIBLE) {
                    guideLeader.setVisibility(View.GONE);
                }
                Intent intent = new Intent(AttendanceMainActivity.this, AttendanceCountActivity.class);
                intent.putExtra("group_id", attendanceData.getGroupId());
                intent.putExtra("form_id", attendanceData.get_id());
                startActivity(intent);
                mCountPopupWindow.dismiss();
            }
        });
        rank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AttendanceMainActivity.this, AttendanceRankActivity.class);
                intent.putExtra("group_id", attendanceData.getGroupId());
                startActivity(intent);
                mCountPopupWindow.dismiss();
            }
        });


        int popWidth = Constants.dip2px(this, 160);
        //int popHeight = Constants.dip2px(mActivity, 168);
        mCountPopupWindow = new PopupWindow(mainView,
              popWidth,
              WindowManager.LayoutParams.WRAP_CONTENT);
        mCountPopupWindow.setFocusable(true);
        mCountPopupWindow.setOutsideTouchable(true);
        int xOffSet = getWindowManager().getDefaultDisplay().getWidth() - popWidth - 10;
        int yOffSet = Constants.dip2px(this, 10);
        mCountPopupWindow.setBackgroundDrawable(new ColorDrawable(
              Color.TRANSPARENT));
        mCountPopupWindow.showAsDropDown(mRlTitleLayout, xOffSet, -yOffSet);
        AlphaAnimation aa = new AlphaAnimation(0.4f, 1.0f);
        aa.setDuration(250);
        ScaleAnimation sa = new ScaleAnimation(0.2f, 1.0f, 0.2f,
              1.0f, Animation.RELATIVE_TO_SELF, 0.91f,
              Animation.RELATIVE_TO_SELF, 0f);
        sa.setDuration(250);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
        mainView.startAnimation(set);
    }

    /**
     * 用户考勤面板, 可能每个团队下有一个考勤界面，这里列出全部，客户端选择第一个展示即可
     */
    private void getAttendanceFace() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        AttendanceFaceMsg attendanceFaceMsg = new AttendanceFaceMsg(mHandler.obtainMessage(GET_ATTENDANCE_FACE), this);
        attendanceFaceMsg.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_FACE;
        attendanceFaceMsg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(attendanceFaceMsg);

    }

    /**
     * 签到或签退
     *
     * @param type 1：签到  2：签退
     */
    private void getAttendanceDoMsg(String type) {
//        if ((mRlWifiLayout.getVisibility() == View.VISIBLE && mTvWifi.getText().toString().startsWith("已连接")) || ((!"4.9E-324".equals(mLatitude + "") && !"4.9E-324".equals(mLongitude + "") && Integer.parseInt(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) <= Integer.parseInt(attendanceData.getDeviation())))) {
        if (mIsAttendanceWifi || ((!"4.9E-324".equals(mLatitude + "") && !"4.9E-324".equals(mLongitude + "") && Integer.parseInt(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) <= Integer.parseInt(attendanceData.getDeviation())))) {
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                  .getInstance().mSid));
            if (attendanceData.getFormType() == 0) {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_FORM_ID, attendanceData.get_id()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_ID, attendanceData.get_id()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, type));
            } else {
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_FORM_ID, mAttendanceSubBean.get_id()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_ID, mAttendanceSubBean.getSub_attendance_id()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, mAttendanceSubBean.getSignType() + ""));
            }
//            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, attendanceData.get_id()));
//            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, type));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_TYPE, attendanceData.getFormType() + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, mLatitude + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, mLongitude + ""));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NAME, deviceName));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WIFI_MAC, wifiMac));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_TYPE, "1"));
            nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NUMBER, deviceId));
            Message msg = mHandler.obtainMessage(GET_ATTENDANCE_DO);
            msg.arg2 = Integer.parseInt(type);
            GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(msg);
            getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_DO;
            getMsgHttpReceiver.mParams = nvps;
            AsynHttpClient.getInstance(this).execEventHttp(getMsgHttpReceiver);
        } else {
            /*if ("381712".equals(PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID, "－1")) || "426402".equals(PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID, "－1"))) {
                showNoticeDlg("您尚未到达考勤点附近!!!!!", type);
            } else {
                showNoticeDlg("您尚未到达考勤点附近\n或Wi-Fi不在范围内,无法签到", 0);
            }*/
            if ("4.9E-324".equals(mLatitude + "") || "4.9E-324".equals(mLongitude + "")) {
                showNoticeDlg("您定位未成功，可能是您尚未开启定位权限", 0);
            } else {
                showNoticeDlg("您尚未到达考勤点附近\n或Wi-Fi不在范围内,无法签到", 0);
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }
    }

    /**
     * 获取两点距离
     *
     * @param latitude
     * @param longitude
     * @return
     */
    private String getDistance(double latitude, double longitude) {
        LatLng start = new LatLng(latitude, longitude);
        LatLng end = new LatLng(mLatitude, mLongitude);
        //  DecimalFormat df = new DecimalFormat("#.0");//保留1位小数
        //return df.format(DistanceUtil.getDistance(start, end) * 1000) + "";
        Log.i(Tag, "签到经纬度 latitude:" + latitude + "---" + "longitude:" + longitude);
        Log.i(Tag, "定位经纬度 latitude:" + mLatitude + "---" + "longitude:" + mLongitude);
        Log.i(Tag, "距离 distance:" + DistanceUtil.getDistance(start, end));
        return String.valueOf(DistanceUtil.getDistance(start, end)).split("\\.")[0];
    }


    private void getCurDeviceMsg() {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        deviceId = telephonyManager.getDeviceId();
        Build bd = new Build();
        deviceName = bd.MODEL;
        Log.i(Tag, "deviceName:" + bd.MODEL + "----" + bd.DEVICE + ":" + bd.PRODUCT);
        Log.i(Tag, "deviceId:" + deviceId);

    }

    private void waitDlgShow() {
        if (mProgressDialog == null) {
            mProgressDialog = AllDialogUtil.getInstance(this).waitDialog("正在定位,请稍后");
//            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

    }

    private void waitDlgDismiss() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }


    /**
     * 设置内容数据
     */
    private void setAttendanceMsg() {
        mSubName = "";
        mIvLocIcon.setImageDrawable(getResources().getDrawable(R.drawable.attendance_msg_icon));
        mTvTitle.setText(attendanceData.getGroupName());

        mTvLocAddress.setText("考勤点:" + attendanceData.getAddress());
        if ("0".equals(attendanceData.getDeviation())) {
            mRlLocLayout.setVisibility(View.GONE);
        } else {
            mRlLocLayout.setVisibility(View.VISIBLE);
            mTvLocNote.setText("(" + attendanceData.getDeviation() + "米内可以签到)");
        }

        if ("4.9E-324".equals(mLatitude + "") || "4.9E-324".equals(mLongitude + "")) {
            mTvLocation.setText("定位失败" + "(" + attendanceData.getDeviation() + "米内有效)");
        } else {
            if (getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude())).length() > 3) {
                mTvLocation.setText("当前定位距离考勤地点" + Double.parseDouble(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) / 1000 + "千米" + "(" + attendanceData.getDeviation() + "米内有效)");
            } else {
                mTvLocation.setText("当前定位距离考勤地点" + getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude())) + "米" + "(" + attendanceData.getDeviation() + "米内有效)");
            }
            if (Integer.parseInt(getDistance(Double.parseDouble(attendanceData.getLatitude()), Double.parseDouble(attendanceData.getLongitude()))) <= Integer.parseInt(attendanceData.getDeviation())) {
                mIvLocIcon.setImageDrawable(getResources().getDrawable(R.drawable.attendance_iv_loc_ok));
            } else {
                mIvLocIcon.setImageDrawable(getResources().getDrawable(R.drawable.attendance_msg_icon));
            }
        }


        setWifiData();

        if (attendanceData.getFormType() == 0) {
            mLayoutAttendance.setVisibility(View.VISIBLE);
            mLvSubClass.setVisibility(View.GONE);
            mTvNullSub.setVisibility(View.GONE);

            long currentTime = System.currentTimeMillis();
            if (!StringUtil.isEmpty(attendanceData.getNoonStartTime()) && !StringUtil.isEmpty(attendanceData.getNoonEndTime())) {
                mLayoutNoon.setVisibility(View.VISIBLE);

                mNoonFlag = 1;
                mTvSignInTitle.setText("上午 上班");
                mTvSignOutTitle.setText("下午 下班");

                mTvSignNoonInTime.setText(attendanceData.getNoonStartTime());
                mTvSignNoonOutTime.setText(attendanceData.getNoonEndTime());

                if (!"0".equals(attendanceData.getNoonSignOutTime())) {
                    mIvSignNoonOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                    mTvSignNoonOut.setVisibility(View.GONE);
                    mTvSignNoonOutOk.setVisibility(View.VISIBLE);
                    mTvSignNoonOutOk.setText("已打卡 " + DateUtil.getHourAndMin(Long.parseLong(attendanceData.getNoonSignOutTime()) * 1000));

                    if (isWordDay(attendanceData.getWorkDate())) {

                        if (compareDate(attendanceData.getNoonEndTime(), attendanceData.getNoonSignOutTime())) {
                            mTvSignNoonOutOk.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            mTvSignNoonOutOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                        }
                    }
                } else {
                    mTvSignNoonOutOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                    mTvSignNoonOut.setVisibility(View.VISIBLE);
                    mTvSignNoonOutOk.setVisibility(View.GONE);

                    if (compareDate(currentTime / 1000 + "", attendanceData.getStartWorkTime()) && compareDate(attendanceData.getNoonStartTime(), currentTime / 1000 + "")) {
                        mIvSignNoonOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out));
                        mTvSignNoonOut.setEnabled(true);
                    } else {
                        mIvSignNoonOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                        mTvSignNoonOut.setEnabled(false);
                    }

                }

                if (!"0".equals(attendanceData.getNoonSignInTime())) {
                    mIvSignNoonIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                    mTvSignNoonIn.setVisibility(View.GONE);
                    mTvSignNoonInOk.setVisibility(View.VISIBLE);
                    mTvSignNoonInOk.setText("已打卡 " + DateUtil.getHourAndMin(Long.parseLong(attendanceData.getNoonSignInTime()) * 1000));

                    if (isWordDay(attendanceData.getWorkDate())) {

                        if (compareDate(attendanceData.getNoonSignInTime(), attendanceData.getNoonStartTime())) {
                            mTvSignNoonInOk.setTextColor(getResources().getColor(R.color.red));
                        } else {
                            mTvSignNoonInOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                        }
                    }
                } else {
                    mTvSignNoonInOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                    mTvSignNoonIn.setVisibility(View.VISIBLE);
                    mTvSignNoonInOk.setVisibility(View.GONE);

                    // 中午签到有效时间在，签到前半小时 到 签到时间
                    int noonStartWorkHour = Integer.parseInt(attendanceData.getNoonStartTime().split(":")[0]);
                    int noonStartWorkMinute = Integer.parseInt(attendanceData.getNoonStartTime().split(":")[1]);
                    if (noonStartWorkMinute >= 30) {
                        noonStartWorkMinute -= 30;
                    } else {
                        noonStartWorkMinute += 30;
                        if (noonStartWorkHour != 0) {
                            noonStartWorkHour -= 1;
                        } else {
                            noonStartWorkHour = 23;
                        }
                    }
                    if (compareDate(currentTime / 1000 + "", noonStartWorkHour + ":" + noonStartWorkMinute) && compareDate(attendanceData.getEndWorkTime(), currentTime / 1000 + "")) {
                        mIvSignNoonIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in));
                        mTvSignNoonIn.setEnabled(true);
                    } else {
                        mIvSignNoonIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                        mTvSignNoonIn.setEnabled(false);

                    }

                }


            } else {
                mLayoutNoon.setVisibility(View.GONE);
                mNoonFlag = 0;
                mTvSignInTitle.setText("上班");
                mTvSignOutTitle.setText("下班");
            }

            mTvSignInTime.setText(attendanceData.getStartWorkTime());
            mTvSignOutTime.setText(attendanceData.getEndWorkTime());

            if (!"0".equals(attendanceData.getSignInTime())) {
                mIvSignIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                mTvSignIn.setVisibility(View.GONE);
                mTvSignInOk.setVisibility(View.VISIBLE);
                mTvSignInOk.setText("已打卡 " + DateUtil.getHourAndMin(Long.parseLong(attendanceData.getSignInTime()) * 1000));

                if (isWordDay(attendanceData.getWorkDate())) {
                    if (compareDate(attendanceData.getSignInTime(), attendanceData.getStartWorkTime())) {
                        mTvSignInOk.setTextColor(getResources().getColor(R.color.red));
                    } else {
                        mTvSignInOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                    }
                }
            } else {

                mTvSignInOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                mTvSignIn.setVisibility(View.VISIBLE);
                mTvSignInOk.setVisibility(View.GONE);

                if ((mNoonFlag == 0 && compareDate(attendanceData.getEndWorkTime(), currentTime / 1000 + ""))
                      || (mNoonFlag == 1 && compareDate(attendanceData.getNoonEndTime(), currentTime / 1000 + ""))) {
                    mIvSignIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in));
                    mTvSignIn.setEnabled(true);
                } else {
                    mIvSignIn.setImageDrawable(getResources().getDrawable(R.drawable.sign_in_ok));
                    mTvSignIn.setEnabled(false);
                }

            }


            if (!"0".equals(attendanceData.getSignOutTime())) {
                mIvSignOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                mTvSignOut.setVisibility(View.GONE);
                mTvSignOutOk.setVisibility(View.VISIBLE);
                mTvSignOutOk.setText("已打卡 " + DateUtil.getHourAndMin(Long.parseLong(attendanceData.getSignOutTime()) * 1000));

                if (isWordDay(attendanceData.getWorkDate())) {
                    if (compareDate(attendanceData.getEndWorkTime(), attendanceData.getSignOutTime())) {
                        mTvSignOutOk.setTextColor(getResources().getColor(R.color.red));
                    } else {
                        mTvSignOutOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                    }
                }
            } else {

                mTvSignOutOk.setTextColor(getResources().getColor(R.color.schedule_notbusy_text));
                mTvSignOut.setVisibility(View.VISIBLE);
                mTvSignOutOk.setVisibility(View.GONE);

                if ((mNoonFlag == 0 && compareDate(currentTime / 1000 + "", attendanceData.getStartWorkTime()))
                      || (mNoonFlag == 1 && compareDate(currentTime / 1000 + "", attendanceData.getNoonStartTime()))) {
                    mIvSignOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out));
                    mTvSignOut.setEnabled(true);

                } else {
                    mIvSignOut.setImageDrawable(getResources().getDrawable(R.drawable.sign_out_ok));
                    mTvSignOut.setEnabled(false);

                }

            }

            if (1 == (attendanceData.getIs_legwork())) {
                mTvLegworkIn.setBackgroundResource(R.drawable.attendance_button_selector);
            } else {
                mTvLegworkIn.setBackgroundResource(R.drawable.sign_button_normal);
            }
        } else {

            mTvNullSub.setVisibility(View.GONE);
            mLayoutAttendance.setVisibility(View.GONE);
            mLvSubClass.setVisibility(View.VISIBLE);

            mSubClass = attendanceData.getSubFormList();
            if (mSubClass == null) {
                String sub_forms = attendanceData.getSubForms();
                mSubClass = new ArrayList<>();
                if (StringUtil.isEmpty(sub_forms)) {
                    return;
                }
                try {
                    JSONArray subs = new JSONArray(sub_forms);
                    long todayTime = getDayBegin();
                    long currentTime = System.currentTimeMillis() / 1000;
                    for (int i = 0; i < subs.length(); i++) {
                        JSONObject sub = subs.getJSONObject(i);
                        mSubName = sub.getString("sub_name");
                        JSONObject records = sub.getJSONObject("records");

                        String start_work_time = sub.getString("start_work_time");
                        String end_work_time = sub.getString("end_work_time");
                        String noon_end_time = "";
                        String noon_start_time = "";
                        if (sub.has("noon_end_time") && !StringUtil.isEmpty(sub.getString("noon_end_time"))) {
                            noon_end_time = sub.getString("noon_end_time");
                            noon_start_time = sub.getString("noon_start_time");
                        }
                        long time1 = records.getLong("1");
                        long time4 = records.getLong("2");
                        long time2 = 0;
                        long time3 = 0;
                        if (records.has("3")) {
                            time2 = records.getLong("3");
                            time3 = records.getLong("4");
                        }

                        long date = sub.getLong("date");

                        /*
                        排班制员工打卡的时间限制规则:

                        1天2次打卡时,上班打卡时间为 X-1,X+1,下班时间为,X-1,X+3,
                        比如:9:00-16:00, 上班打卡的时间为8:00-10:00,下班打卡的时间为:15:00-19:00

                        1天4次打卡时,早上上班时间为X-1,X+1,早上下班时间为X-1,X+1,下午上班时间为X-0.5,X+1,下午下班时间为X-1,X+3.
                        比如:9:00-12:00;13:30-18:00, 上午上班为8:00-10:00,上午下班为11:00-13:00,下午上班为:13:00-14:30,下午下班为:17:00-21:00

                        当不允许打卡时,增加2个状态.未到打卡时间的状态标识为”未启用”;打卡时间过期的状态标识为”已过期”
                        */

                        // TODO 签到时间1
                        AttendanceSubBean bean1 = new AttendanceSubBean();
                        bean1.setSub_attendance_id(sub.getString("sub_attendance_id"));
                        bean1.set_id(sub.getString("_id"));
                        bean1.setSub_name(sub.getString("sub_name"));
                        bean1.setSignType(1);
                        bean1.setTimeString(start_work_time);
                        bean1.setDate(date);

                        // TODO 签退时间1
                        AttendanceSubBean bean2 = new AttendanceSubBean();
                        bean2.setSub_attendance_id(sub.getString("sub_attendance_id"));
                        bean2.set_id(sub.getString("_id"));
                        bean2.setSub_name(sub.getString("sub_name"));
                        bean2.setSignType(3);
                        bean2.setDate(date);

                        // TODO 签到时间2
                        AttendanceSubBean bean3 = new AttendanceSubBean();
                        bean3.setSub_attendance_id(sub.getString("sub_attendance_id"));
                        bean3.set_id(sub.getString("_id"));
                        bean3.setSub_name(sub.getString("sub_name"));
                        bean3.setSignType(4);
                        bean3.setDate(date);

                        // TODO 签退时间2
                        AttendanceSubBean bean4 = new AttendanceSubBean();
                        bean4.setSub_attendance_id(sub.getString("sub_attendance_id"));
                        bean4.set_id(sub.getString("_id"));
                        bean4.setSub_name(sub.getString("sub_name"));
                        bean4.setSignType(2);
                        bean4.setTimeString(end_work_time);
                        bean4.setDate(date);

                        bean1.setDate(sub.getLong("date"));
                        bean1.setSignTime(time1);
                        bean1.setTime(getTime(todayTime, date, start_work_time));
                        bean1.setLastTime(bean1.getTime() - 60 * 60);
                        bean1.setNextTime(bean1.getTime() + 60 * 60);

                        /*if (sub.has("noon_end_time") && !StringUtil.isEmpty(sub.getString("noon_end_time"))){
                            bean1.setNextTime(getTime(todayTime,date,noon_end_time));
                        }else{
                            bean1.setNextTime(getTime(todayTime,date,end_work_time));
                        }*/

                        if (time1 == 0) {
                            bean1.setSign(false);
                            if (currentTime > bean1.getLastTime() && currentTime < bean1.getNextTime()) {
                                bean1.setEnable(true);
                            } else {
                                bean1.setEnable(false);
                                if (bean1.getTime() < currentTime) {
                                    bean1.setEnableState(-1);
                                } else {
                                    bean1.setEnableState(1);
                                }
                            }

                        } else {
                            bean1.setSign(true);
                            if (time1 > bean1.getTime()) {
                                bean1.setLate(true);
                            } else {
                                bean1.setLate(false);
                            }
                        }

                        mSubClass.add(bean1);

                        bean4.setDate(date);
                        bean4.setTime(getTime(todayTime, date, end_work_time));
                        bean4.setSignTime(time4);

                        if (sub.has("noon_end_time") && !StringUtil.isEmpty(sub.getString("noon_end_time"))) {
                            bean2.setTime(getTime(todayTime, date, noon_end_time));

                            bean2.setLastTime(bean2.getTime() - 60 * 60);
                            bean2.setNextTime(bean2.getTime() + 60 * 60);
//                            bean2.setLastTime(getTime(todayTime,date,start_work_time));
//                            bean2.setNextTime(getTime(todayTime,date,noon_start_time));

                            bean2.setSignTime(time2);
                            bean2.setTimeString(noon_end_time);

                            if (time2 == 0) {
                                bean2.setSign(false);
                                if (currentTime > bean2.getLastTime() && currentTime < bean2.getNextTime()) {
                                    bean2.setEnable(true);
                                } else {
                                    bean2.setEnable(false);
                                    if (bean2.getTime() < currentTime) {
                                        bean2.setEnableState(-1);
                                    } else {
                                        bean2.setEnableState(1);
                                    }
                                }

                            } else {
                                bean2.setSign(true);
                                if (time2 >= bean2.getTime()) {
                                    bean2.setLate(true);
                                } else {
                                    bean2.setLate(false);
                                }
                            }
                            mSubClass.add(bean2);

                            bean3.setTime(getTime(todayTime, date, noon_start_time));

                            bean3.setLastTime(bean3.getTime() - 30 * 60);
                            bean3.setNextTime(bean3.getTime() + 60 * 60);

//                            bean3.setLastTime(getTime(todayTime,date,noon_start_time) - 30*60);
//                            bean3.setNextTime(getTime(todayTime,date,end_work_time));
                            bean3.setSignTime(time3);
                            bean3.setTimeString(noon_start_time);

                            if (time3 == 0) {
                                bean3.setSign(false);
                                if (currentTime > bean3.getLastTime() && currentTime < bean3.getNextTime()) {
                                    bean3.setEnable(true);
                                } else {
                                    bean3.setEnable(false);
                                    if (bean3.getTime() < currentTime) {
                                        bean3.setEnableState(-1);
                                    } else {
                                        bean3.setEnableState(1);
                                    }
                                }

                            } else {
                                bean3.setSign(true);
                                if (time3 > bean3.getTime()) {
                                    bean3.setLate(true);
                                } else {
                                    bean3.setLate(false);
                                }
                            }
                            mSubClass.add(bean3);
                        }

                        bean4.setLastTime(bean4.getTime() - 60 * 60);
                        bean4.setNextTime(bean4.getTime() + 180 * 60);

                        if (time4 == 0) {
                            bean4.setSign(false);
                            if (currentTime > bean4.getLastTime() && currentTime < bean4.getNextTime()) {
                                bean4.setEnable(true);
                            } else {
                                bean4.setEnable(false);
                                if (bean4.getTime() < currentTime) {
                                    bean4.setEnableState(-1);
                                } else {
                                    bean4.setEnableState(1);
                                }
                            }
                        } else {
                            bean4.setSign(true);
                            if (time4 >= bean4.getTime()) {
                                bean4.setLate(true);
                            } else {
                                bean4.setLate(false);
                            }
                        }
                        mSubClass.add(bean4);

                    }

                    // TODO 外勤签到
                    AttendanceSubBean bean5 = new AttendanceSubBean();
                    bean5.setSignType(-1);
                    if (attendanceData.getIs_legwork() == 1) {
                        bean5.setEnable(true);
                    } else {
                        bean5.setEnable(false);
                    }
                    mSubClass.add(bean5);

                    attendanceDatas.remove(attendanceData);
                    attendanceData.setSubFormList(mSubClass);
                    attendanceDatas.add(attendanceData);


                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            if (mSubSignAdapter == null) {
                mSubSignAdapter = new AttendanceSubSignAdapter(this);
                mLvSubClass.setAdapter(mSubSignAdapter);
            }
            mSubSignAdapter.bindData(mSubClass);
            mSubSignAdapter.setSignListener(this);
            if (mSubClass.size() == 1) {
                mTvNullSub.setVisibility(View.VISIBLE);
                mTvNullSub.setText("今日暂无排班");
            }


        }

    }

    /**
     * 获取真正签到的时间戳
     * @param todayTime 当天0点的时间戳
     * @param date 班次开始的日期的时间戳
     * @param time 上班时间 -表示次日
     * @return
     */
    private long getTime(long todayTime, long date, String time) {

        int hour = 0;
        int minute = 0;
        if (todayTime > date) { // 昨天的班次
            if (time.contains("-")) {//时间是次日
                time = time.replace("-", "");
                hour = Integer.parseInt(time.split(":")[0]);
                minute = Integer.parseInt(time.split(":")[1]);
                return todayTime + hour * 60 * 60 + minute * 60; // hour 可能为0

            } else {
                hour = Integer.parseInt(time.split(":")[0]);
                minute = Integer.parseInt(time.split(":")[1]);
                return date + hour * 60 * 60 + minute * 60;
            }
        } else { // 今天的班次

            if (time.contains("-")) {
                time = time.replace("-", "");
                hour = Integer.parseInt(time.split(":")[0]);
                minute = Integer.parseInt(time.split(":")[1]);
                return todayTime + mOneDayTime + hour * 60 * 60 + minute * 60;

            } else {
                hour = Integer.parseInt(time.split(":")[0]);
                minute = Integer.parseInt(time.split(":")[1]);
                return date + hour * 60 * 60 + minute * 60;
            }
        }

    }

    /*private long getDate(long todayTime,long date,String time){

        if (todayTime > date){ // 昨天
            if (time.contains("-")){
                return todayTime;
            }else{
                return date;
            }
        }else{ // 今天
            if (time.contains("-")){
                return todayTime + mOneDayTime;
            }else{
                return date;
            }
        }
    }*/


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 100:
                    attendanceData = (AttendanceData) data.getSerializableExtra("attendance");
                    break;
            }
        }
    }

    /**
     * 获取当天的日期时间戳
     *
     * @return
     */
    public long getDayBegin() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 001);
        return cal.getTimeInMillis() / 1000;
    }


    public void showNoticeDlg(String msg, final int type) {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        if (type == 0) {
            mDialogUtil.titleMsgBtnStyle("提示", msg, "知道了");
        } else {
            mDialogUtil.titleMsgBtnClick("提示", msg, okText, cancelText);
        }
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                if (type != 0) {
                    refreshLoction(type + "");
                }

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    //个人定制
    public void showNoticeDlg(String msg, final String type) {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        String okText = this.getString(R.string.label_btn_ok);
        String cancelText = this.getString(R.string.cancel);
        mDialogUtil.titleMsgBtnClick("提示", msg, okText, cancelText);
        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                List<NameValuePair> nvps = new ArrayList<NameValuePair>();
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
                      .getInstance().mSid));
                if (attendanceData.getFormType() == 0) {
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_FORM_ID, attendanceData.get_id()));
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_ID, attendanceData.get_id()));
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, type));
                } else {
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_FORM_ID, mAttendanceSubBean.get_id()));
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_AT_ID, mAttendanceSubBean.getSub_attendance_id()));
                    nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, mAttendanceSubBean.getSignType() + ""));
                }

//                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_FORM_ID, attendanceData.get_id()));
//                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_ATTENDANCE_TYPE, type + ""));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_TYPE, attendanceData.getFormType() + ""));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, attendanceData.getLatitude()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, attendanceData.getLongitude()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NAME, deviceName));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_WIFI_MAC, attendanceData.getWifiMsg()));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_TYPE, "1"));
                nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_DEVICE_NUMBER, deviceId));
                Message msg = mHandler.obtainMessage(GET_ATTENDANCE_DO);
                msg.arg2 = Integer.parseInt(type);
                GetMsgHttpReceiver getMsgHttpReceiver = new GetMsgHttpReceiver(msg);
                getMsgHttpReceiver.mApi = AsynHttpClient.API_EVENT_ATTENDANCE_DO;
                getMsgHttpReceiver.mParams = nvps;
                AsynHttpClient.getInstance(AttendanceMainActivity.this).execEventHttp(getMsgHttpReceiver);

            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

    /**
     * 判断工作日
     *
     * @param workDate
     * @return
     */
    private boolean isWordDay(String workDate) {
        String workDay[] = workDate.split(",");
        boolean flag = false;
        for (int i = 0; i < workDay.length; i++) {
            if (workDay[i].equals(DateUtil.getWeek() + "")) {
                flag = true;
                break;
            }
        }
        return flag;
    }


    private void setWifiData() {
        try {
            if (attendanceData != null) {
                String wifiMsg = attendanceData.getWifiMsg();
                if (!StringUtil.isEmpty(wifiMsg)) {
                    JSONArray jsonArray = new JSONArray(wifiMsg);
                    if (jsonArray.length() > 0) {
                        mIsAttendanceWifi = false;
                        WifiInfo wifiInfo = NetworkUtil.getWifiInfo(this);

                        mRlWifiLayout.setVisibility(View.VISIBLE);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            wifiMac = wifiInfo.getBSSID();
                            if (jsonObject.getString("wifi_mac").equals(wifiInfo.getBSSID())) {
                                mIsAttendanceWifi = true;
                            }

                        }
                        if (StringUtil.isEmpty(wifiInfo.getBSSID())) {
                            mTvWifi.setText("Wi-Fi未连接");
                        } else if (mIsAttendanceWifi) {
                            mTvWifi.setText("已连接考勤Wi-Fi:" + wifiInfo.getSSID());
                        } else {
                            mTvWifi.setText("未连接考勤Wi-Fi");
                        }

                    } else {
                        mRlWifiLayout.setVisibility(View.GONE);
                    }
                } else {
                    mRlWifiLayout.setVisibility(View.GONE);
                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断 网络状况
     * 判断 wi-fi是否正确
     */
    private boolean checkAttendanceData() {

        if (!NetworkUtil.checkNetwork(this)) {
            Toast.makeText(AttendanceMainActivity.this, "网络异常，请检查网络", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (attendanceData == null) {
            Toast.makeText(AttendanceMainActivity.this, "您不属于任何考勤点，无法进行考勤操作", Toast.LENGTH_SHORT).show();
            return false;
        }

        if ("381712".equals(PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID, "－1")) || "426402".equals(PreferenceUtil.getInstance(this).getString(PreferenceUtil.CLIENT_USEID, "－1"))) {
            return true;
        }

        if ("0".equals(attendanceData.getDeviation()) && !mIsAttendanceWifi) {
            Toast.makeText(AttendanceMainActivity.this, "考勤失败，未连上考勤Wi-Fi", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    @Override
    public void signAction(AttendanceSubBean data, int position) {
        int type = data.getSignType();
        if (type == -1) {
            toLegworkActivity();
        } else {
            if (!checkAttendanceData()) {
                return;
            }
            mAttendanceSubBean = data;
            mPosition = position;
            if (attendanceData != null) {
                if (mAttendanceSubBean.isSign()) {
                    Toast.makeText(this, "您今天已经打卡，请勿重复打卡", Toast.LENGTH_LONG).show();
                } else {
                    long currentTime = System.currentTimeMillis() / 1000;
                    if (type == 1 || type == 4) {
                        if (currentTime > mAttendanceSubBean.getTime()) {
                            showNoticeDlg("现在是" + DateUtil.getHourAndMin(currentTime * 1000) + "分,您已迟到\n是否确认签到", type);
                        } else {
                            refreshLoction(type + "");
                        }
                    } else {
                        if (currentTime < mAttendanceSubBean.getTime()) {
                            showNoticeDlg("现在是" + DateUtil.getHourAndMin(currentTime * 1000) + "分,还未下班\n您是否确认签退", type);
                        } else {
                            refreshLoction(type + "");
                        }
                    }
                }

            }
        }
    }
}
